<template>
  <div>
    <el-button-group>
      <el-button plain icon="el-icon-plus" @click="handleAdd">添加指标</el-button>
    </el-button-group>
    <h3 class="table-title">会议指标列表</h3>
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="筛选指标类型">
        <ConferTypeSelector v-model="conferTypeValue" :multi="true" />
      </el-form-item>
    </el-form>
    <el-table
      v-if="conferTypesDict"
      v-loading="tableLoading"
      :data="TableData"
      highlight-current-row
    >
      <el-table-column label="序号" type="index" fixed="left" width="50">
        <template slot-scope="scope">
          <span>{{ scope.$index + page.pageIndex*page.pageSize + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" sortable width="120" prop="conferenceType">
        <template slot-scope="{row}">
          <p
            v-for="(item, index) in row.conferenceType"
            :key="index"
          >{{ conferTypesDict[item]?conferTypesDict[item].alias:row.conferenceType }}</p>
          <el-tag v-if="row.isDefault">默认</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="落实单位">
        <template slot-scope="{row}">
          <CompanyFormItem :id="row.companyCode" />
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title" width="150" show-overflow-tooltip />
      <el-table-column label="周期">
        <template slot-scope="{row}">
          <span>{{ rankTypesDict[row.period]?rankTypesDict[row.period].alias:row.period }}</span>
        </template>
      </el-table-column>
      <el-table-column label="指标">
        <el-table-column label="时长" prop="requireHours" />
        <el-table-column label="次数" prop="requireTimes" />
      </el-table-column>
      <el-table-column label="启用时间" width="120">
        <template slot-scope="{row}">{{ row.start&&(parseTime(row.start,'{y}-{m}-{d}')) }}</template>
      </el-table-column>
      <el-table-column label="失效时间" width="150">
        <template slot-scope="{row}">
          <span>
            {{ row.end&&(parseTime(row.end,'{y}-{m}-{d}')) }}
            <el-tag :type="isOutDate(row.end)?'success':'danger'">{{ isOutDate(row.end)?'有效':'失效' }}</el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="description" width="200" show-overflow-tooltip />
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :pagesetting.sync="page" :total-count="totalCount" />
    <el-dialog :visible.sync="dialogFlag" :title="dialogTitle">
      <el-form
        v-if="conferTypesArray&&rankTypesArray"
        ref="indicatorForm"
        :model="FormData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="FormData.title" />
        </el-form-item>
        <el-form-item label="类型" prop="conferenceType" required>
          <el-select v-model="FormData.conferenceType" multiple collapse-tags>
            <el-option
              v-for="item in conferTypesArray"
              :key="item.index"
              :label="item.alias"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="周期" prop="period" required>
          <el-select v-model="FormData.period">
            <el-option
              v-for="item in rankTypesArray"
              :key="item.index"
              :label="item.alias"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="落实单位" prop="companyCode">
          <CompanySelector :code.sync="FormData.companyCode" />
        </el-form-item>
        <el-form-item label="次数（指标）" prop="requireTimes">
          <el-input v-model.number="FormData.requireTimes" placeholder="时长和次数至少填写一个" />
        </el-form-item>
        <el-form-item label="时长（指标）" prop="requireHours">
          <el-input v-model.number="FormData.requireHours" />
        </el-form-item>
        <el-form-item label="启用时间" prop="start">
          <el-date-picker
            v-model="FormData.start"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="失效时间" prop="end">
          <el-date-picker
            v-model="FormData.end"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="指标描述" prop="description">
          <el-input v-model="FormData.description" type="textarea" />
        </el-form-item>
        <el-form-item label="设为默认指标">
          <el-switch v-model="FormData.isDefault" active-color="#13ce66" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(FormData)">立即提交</el-button>
          <el-button @click="resetForm(FormData)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import {
  postIndicator,
  deleteIndicator,
  getIndicatorList
} from '@/api/zzxt/party-conference/confer-indicator'

import { parseTime, arrayToBinaryFlag, binaryFlagToArray } from '@/utils'
import { isOutDate } from '@/views/HomePage/common'
export default {
  name: 'IndicatorManage',
  components: {
    Pagination: () => import('@/components/Pagination'),
    CompanyFormItem: () => import('@/components/Company/CompanyFormItem'),
    ConferTypeSelector: () =>
      import('@/components/Party/ConferType/ConferTypeSelector'),
    CompanySelector: () => import('@/components/Company/CompanySelector')
  },
  data: () => ({
    TableData: null,
    page: { pageIndex: 0, pageSize: 10 },
    totalCount: 0,
    tableLoading: false,
    dialogTitle: '',
    dialogFlag: false,
    submitLoading: false,
    FormData: {},
    conferTypeValue: [],
    formRules: {
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
      conferenceType: [
        { required: true, message: '请选择类型', trigger: ['blur', 'change'] }
      ],
      period: [
        { required: true, message: '请选择周期', trigger: ['blur', 'change'] }
      ],
      requireTimes: [{ type: 'number', message: '次数必须为数字值' }],
      requireHours: [{ type: 'number', message: '时长必须为数字值' }],
      start: [{ required: true, message: '请选择启用时间', trigger: 'blur' }],
      end: [{ required: true, message: '请选择失效时间', trigger: 'blur' }]
    }
  }),
  computed: {
    currentCompany() {
      return this.$store.state.user.globalCompany
    },
    conferTypesArray() {
      const ar = this.$store.state.party.conferTypes
      if (ar && !Array.isArray(ar)) {
        throw Error(JSON.stringify({ message: '错误类型conferTypesArray', ar }))
      }
      return ar
    },
    conferTypesDict() {
      return this.$store.state.party.conferTypesDict
    },
    rankTypesArray() {
      return this.$store.state.party.RankType
    },
    rankTypesDict() {
      return this.$store.state.party.RankTypeDict
    }
  },
  watch: {
    conferTypesArray: {
      handler(val) {
        if (!val) return
        this.conferTypeValue = val.filter(i => i.value > 0).map(i => i.value)
      },
      immediate: true
    },
    conferTypeValue: {
      handler(val) {
        this.refresh()
      },
      immediate: true,
      deep: true
    },
    currentCompany: {
      handler(val) {
        if (val) this.refresh()
      },
      immediate: true
    }
  },
  mounted() {
    this.$store.dispatch('party/initDictionary')
    this.FormData.companyCode = this.$store.state.user.globalCompany
    this.refresh()
  },
  methods: {
    isOutDate,
    parseTime,
    refresh() {
      this.tableLoading = true
      const page = this.page
      const conferenceType = this.conferTypeValue.reduce(
        (prev, cur) => prev | cur,
        0
      )
      const company = this.currentCompany
      getIndicatorList({
        page,
        conferenceType,
        company
      }).then(data => {
        const list = data.list.map(item => {
          const type = item.conferenceType
          item.conferenceType = binaryFlagToArray(type)
          return item
        })
        this.TableData = list
        this.totalCount = data.totalCount
        this.tableLoading = false
      })
    },
    handleEdit(row) {
      this.FormData = row
      this.dialogTitle = '编辑指标'
      this.dialogFlag = true
    },
    handleAdd() {
      this.dialogTitle = '添加指标'
      this.dialogFlag = true
      this.FormData = {}
    },
    submitForm(form) {
      this.$refs['indicatorForm'].validate(valid => {
        if (valid) {
          const type = arrayToBinaryFlag(form.conferenceType)
          form.conferenceType = type
          this.submitLoading = true
          postIndicator(Object.assign(form)).then(data => {
            this.$message.success('提交成功')
            this.refresh()
            this.submitLoading = false
            this.dialogFlag = false
          })
        } else {
          this.$message.error('请检查填写内容，确认必填项已经填写')
          return false
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除？').then(_ => {
        deleteIndicator(row.id, this.currentCompany).then(item => {
          this.$message.success('删除成功')
          this.refresh()
        })
      })
    },
    resetForm(form) {
      this.$refs['indicatorForm'].resetFields()
      form = {}
    }
  }
}
</script>
<style scoped>
.table-title {
  font-weight: 500px;
  margin-top: 1rem;
  margin-bottom: 1rem;
  text-align: center;
}
</style>
